package task3

import grails.converters.JSON

class OrganizationController {

    def organizationService

    def index() { redirect(action: org1) }

    def org1 = {}

    def jsonDynamic = {
        render organizationService.parseInitialTreeToJson()
    }

    def jsonUpdateNodeName = {
        def objectFound = organizationService.getNodeInDatabase(params)

        if (!objectFound) {
            render([success: false] as JSON)
        } else {
            objectFound.name = params.newName
            objectFound.validate()
            if (objectFound.hasErrors()) {
                objectFound.discard()
                render([success: false,msg:organizationService.getFailureMessage()] as JSON)
            } else {
                objectFound.save(flush: true)
                render([success: true] as JSON)
            }
        }
    }


    def jsonDeleteNode = {
        def objectFound = organizationService.getNodeInDatabase(params)
        if (objectFound != null) {
            objectFound.delete()
        }
        render([success: true] as JSON)
    }


    def saveDataFromForm = {
        def resultMap
        if (params.id == null) {
            resultMap = organizationService.saveNewNode(params)
        } else {
            resultMap = organizationService.updateNode(params)
        }
        render(resultMap as JSON)
    }


    def loadDataToForm = {

        render(organizationService.loadNodeData(params) as JSON)
    }

    def testDep ={
        def dep = Department.get(1)
        render dep.name
    }
}